package com.wswy.wzcx.ui.main.garage

import android.arch.lifecycle.Observer
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewPager
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Space
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.getStatusColor
import com.wswy.wzcx.model.home.ExtModule
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.module.base.removeFirst
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.car.remind.RemindActivity
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.widget.home.HomeCategoryLayout
import com.wswy.wzcx.widget.home.ModuleItemClickListener
import com.wswy.wzcx.widget.utils.ScalePageTransformer
import kotlinx.android.synthetic.main.fragment_garage_cars.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView


/**
 * 已登录  有车 车库
 */
class CarsFragment : CBaseFragment() {

    private companion object {
        private const val TAG = "CarsFragment"
    }

    private lateinit var garageViewModel: GarageViewModel

    private lateinit var adapter:GarageCarsAdapter
    private lateinit var titleNavigator : CommonNavigator

    private val pageTransformer = ScalePageTransformer()


    private var currentCar:UserCarInfo? = null

    private val datas = arrayListOf<UserCarInfo>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val inflate = inflater.inflate(R.layout.fragment_garage_cars, container, false)
        inflate.findViewById<View?>(R.id.fl_top)?.let {
            (it.layoutParams as? ViewGroup.MarginLayoutParams)?.run {
                topMargin += UiUtils.getStatusBarHeight(it.context)
                it.layoutParams = this
            }
        }

        return inflate
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        garageViewModel = provideViewModel(GarageViewModel::class.java)
        garageViewModel.onCreate()

        layout_root.background = CarsContentDrawable(ContextCompat.getColor(layout_root.context,R.color.dark_bg_color))

        adapter = GarageCarsAdapter(datas)

        viewPager.offscreenPageLimit = 3
        viewPager.setPageTransformer(false,pageTransformer)
        viewPager.adapter = adapter


        initViews()

        garageViewModel.loadMyCars()

        //车辆数据
        garageViewModel.getUserCarsLiveData().observe(this, Observer {


            it?.run {

                if (!inLoading()){

                    if (isOk() && data != null){
                        fillData(data)
                    }else{
                        ToastUtils.showText(message)
                    }
                    refreshLayout.finishRefresh(1000)
                }

            }
        })

        //配置栏目
        garageViewModel.getTabConfLiveData().observe(this, Observer {
            showTabConf(it)
        })


        garageViewModel.carUpdateCallback = {userCarInfo ->
            //修复刷新时动画错误的问题
            pageTransformer.setDisableTransformer(true)

            //更新车辆信息
            //1. 是否添加 还是 更新
            //添加需要加入list
            //更新需要修改list中的对象
            //刷新上下指示器

            val idx = datas.indexOfFirst {
                userCarInfo.id == it.id
            }

            if (idx >= 0) {
                //更新
                if(!userCarInfo.isError){
                    datas[idx] = userCarInfo
                    adapter.pendingUpdate = idx
                }
            } else {
                //添加
                datas.add(userCarInfo)
            }

            notifyCarsUpdate()

            //如果当前显示的就是这个车，立即更新显示的估值投保等信息
            if (userCarInfo.id == currentCar?.id){
                showCurrentCar(userCarInfo)
            }
            pageTransformer.setDisableTransformer(false)
        }

        garageViewModel.carDeleteCallback = {carId ->

            //删除车辆
            //1.删除对应id 2.刷新标题 3.刷新adapter 4.更新指示器点
            datas.iterator().removeFirst { it.id == carId }

            notifyCarsUpdate()

        }

    }



    private fun initViews(){

        //下拉刷新
        refreshLayout.setOnRefreshListener {
            garageViewModel.loadMyCars(true)
            //garageViewModel.loadTabConf()

        }

        //车辆卡片
        initViewCars()

        //新增
        img_add_new.onClick {
            RouterUtils.startAdd(it.context)

            StatTools.sendClick(it.context,StatisticsId.carport_add_have)

        }

        //最新估值
        ll_car_valuation.onClick {
            currentCar?.run {
                RemindActivity.startValuation(it.context,this)

                val sid = if (carExtendInfo?.valuation?.info != null) StatisticsId.carport_value_have else StatisticsId.carport_value_null

                StatTools.sendClick(it.context,sid)

            }
        }

        //下次投保
        ll_next_insurance.onClick {
            currentCar?.run {
                RemindActivity.startInsurance(it.context,this)


                val sid = if (carExtendInfo?.insuranceInfo != null) StatisticsId.carport_insurance_have else StatisticsId.carport_insurance_null

                StatTools.sendClick(it.context,sid)

            }
        }

        //下次年检
        ll_next_inspection.onClick {
            currentCar?.run {
                RemindActivity.startInspection(it.context,this)


                val sid = if (carExtendInfo?.inspection != null) StatisticsId.carport_inspection_have else StatisticsId.carport_inspection_null

                StatTools.sendClick(it.context,sid)

            }
        }

        //驾照扣分
        ll_car_licence.onClick {
            currentCar?.run {
                RouterUtils.startTarget(context,RouterUtils.TYPE_NATIVE,RPaths.jzcf)


                val sid = if (!TextUtils.isEmpty(driverLicense?.score)) StatisticsId.carport_licence_have else StatisticsId.carport_licence_null

                StatTools.sendClick(it.context,sid)


            }
        }

    }

    /**
     * 显示当前车辆估值等信息
     */
    private fun showCurrentCar(userCarInfo: UserCarInfo?){

        if(!isAdded || isFinish || context == null){
            return
        }

        currentCar = userCarInfo

        val context = tv_car_valuation.context

        currentCar?.carExtendInfo?.run {

            valuation?.value?.run {

                val sb = SpannableStringBuilder().append(SpannableString(this))

//                SpannableString("万").run {
//                    setSpan(StyleSpan(Typeface.NORMAL),0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(RelativeSizeSpan(0.6f), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.textColorPrimary_70)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    sb.append(this)
//                }
                tv_car_valuation.text = sb
            }?:kotlin.run {
                tv_car_valuation.text = "--"
            }


            //保险
            insuranceInfo?.run {


                val colors = getStatusColor()
                val sb = SpannableStringBuilder().append(SpannableString(remainDay.toString()).apply {
                    setSpan(ForegroundColorSpan(ContextCompat.getColor(context, colors.numberColor)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

                })

//                SpannableString("天").run {
//                    setSpan(StyleSpan(Typeface.NORMAL),0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(RelativeSizeSpan(0.6f), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(ForegroundColorSpan(ContextCompat.getColor(context,colors.unitColor)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    sb.append(this)
//                }
                tv_car_next_insurance.text = sb

            } ?: kotlin.run {
                tv_car_next_insurance.text = "--"
            }



            //年检
            inspection?.run {

                val colors = getStatusColor()

                val sb = SpannableStringBuilder().append(SpannableString(remainDay.toString()).apply {
                    setSpan(ForegroundColorSpan(ContextCompat.getColor(context, colors.numberColor)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

                })

//                SpannableString("天").run {
//                    setSpan(StyleSpan(Typeface.NORMAL),0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(RelativeSizeSpan(0.6f), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    setSpan(ForegroundColorSpan(ContextCompat.getColor(context, colors.unitColor)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    sb.append(this)
//                }
                tv_car_next_inspection.text = sb
            } ?: kotlin.run {
                tv_car_next_inspection.text = "--"
            }



        }?:kotlin.run {
            tv_car_valuation.text = "--"
            tv_car_next_insurance.text = "--"
            tv_car_next_inspection.text = "--"
            tv_car_licence.text = "--"
        }

        //驾驶证
        userCarInfo?.driverLicense?.score?.run {


            val sb = SpannableStringBuilder().append(SpannableString(this).also {
                if (this.toIntOrNull()?:0 >= 1){
                    //it.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.accentColor3)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                }
            })


//            SpannableString("分").run {
//                setSpan(StyleSpan(Typeface.NORMAL),0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                setSpan(RelativeSizeSpan(0.6f), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.textColorPrimary_40)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                sb.append(this)
//            }

            tv_car_licence.text = sb

        }?:kotlin.run {
            tv_car_licence.text = "--"
        }

    }

    /**
     * 显示配置
     */
    private fun showTabConf(models:Map<String,List<ExtModule>>?){

        val container=  ll_models_container

        container.removeAllViewsInLayout()

        val clickListener = ModuleItemClickListener(StatisticsId.clickCarsModule)

        models?.forEach { (t, u) ->

            HomeCategoryLayout(container.context).apply {
                setBackgroundColor(Color.WHITE)
                setLineMaxItem(4)
                showCategory(t,u)
                setOnItemClickListener(clickListener)
            }.run {
                val  lp = ViewGroup.MarginLayoutParams( ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
                //lp.bottomMargin = SizeUtils.dp2px(10f)
                container.addView(this,lp)

                container.addView(Space(context),ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,SizeUtils.dp2px(10f)))
            }
        }


    }

    private fun initViewCars(){
        titleNavigator = CommonNavigator(context).apply {
            isSkimOver = true
        }

        titleNavigator.adapter = object : CommonNavigatorAdapter() {

            override fun getCount(): Int {
                return datas.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val clipPagerTitleView = ClipPagerTitleView(context)
                clipPagerTitleView.setPadding(SizeUtils.dp2px(12f),0,SizeUtils.dp2px(12f),0)
                clipPagerTitleView.text = datas[index].carNo
                clipPagerTitleView.textSize = SizeUtils.sp2px(18f).toFloat()
                clipPagerTitleView.textColor = ContextCompat.getColor(context,R.color.white50)
                clipPagerTitleView.clipColor = ContextCompat.getColor(context,R.color.white)
                clipPagerTitleView.setOnClickListener { viewPager.currentItem = index }
                return clipPagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator? = null
        }

        magic_indicator.navigator = titleNavigator


        viewPager.clearOnPageChangeListeners()
        ViewPagerHelper.bind(magic_indicator, viewPager)


        viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {

                showCurrentCar(adapter.getItem(position))

            }

        })

    }


    //显示车辆卡片
    private fun fillData(list:List<UserCarInfo>){

        datas.clear()
        datas.addAll(list)

        showCurrentCar(datas.getOrNull(viewPager.currentItem))

        notifyCarsUpdate()
    }


    private fun notifyCarsUpdate(){

        titleNavigator.notifyDataSetChanged()

        adapter.notifyDataSetChanged()

    }

}